/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package tools;

import com.openbrew.openbrewrf.Administration;
import com.openbrew.openbrewrf.Employee;
import com.openbrew.openbrewrf.OBAlarm;
import com.openbrew.openbrewrf.OBReminder;
import java.util.Date;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.persistence.EntityManager;

/**
 *
 * @author chapmand
 */
public class SystemEmailer {
    private Administration admin = null;
        
    private void loadAdmin(EntityManager en){
        admin = en.createNamedQuery("Administration.findAll", Administration.class).getResultList().get(0);
    }
    
    private Properties makePropertiesObject(){
        Properties props = new Properties();
        if(admin.getSMTPAuth()){
            props.put("mail.smtp.auth", "true");
        } else {
            props.put("mail.smtp.auth", "false");
        }
        
        if(admin.getSMTPStartTls()){
            props.put("mail.smtp.starttls.enable", "true");
        } else {
            props.put("mail.smtp.starttls.enable", "false");
        }
        props.put("mail.smtp.host", admin.getSMTPAddress());
        props.put("mail.smtp.port", admin.getSMTPPort());
        return props;
    }
    
    
    private String decryptBillingEmailPassword(final String encStr){
        String decrypted = Encrypter.NAGASAKTI.decrypt(encStr);
        return decrypted;
    }
    
    
    public void sendTestEmail(final EntityManager en){
        loadAdmin(en);
        
        final String username = admin.getBillingEmail();
        final String password = decryptBillingEmailPassword(admin.getBillingEmailPass());
        
        final String subjectLine = "Automated reminder from openBrew ";
        final String body = "TEST TEST TEST!!!";
        
        Properties props = makePropertiesObject();
        
        Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
                  protected PasswordAuthentication getPasswordAuthentication() {
                          return new PasswordAuthentication(username, password);
                  }
            });
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(admin.getBillingEmail()));

            final String emailAddress = "don@grimmbrosbrewhouse.com";
            message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(emailAddress));
            
            message.setSubject(subjectLine);

            //Create Message Part
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);

            //Create a multipar message
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            //Send the complete message parts.
            message.setContent(multipart);
            Transport.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
    
    
    public void SendReminderNotificationMail(final OBReminder rmdr, final OBAlarm alarm, final Date date, final EntityManager en){
        loadAdmin(en);
        
        final String username = admin.getBillingEmail();
        final String password = decryptBillingEmailPassword(admin.getBillingEmailPass());
        
        final String subjectLine = "Automated reminder from openBrew ";
        final String body = "Task: " + rmdr.getReminderText() + "\n"
                + "Due: " + date.toString() + "\n"
                + "Notes: " + alarm.getAlarmText();
        
        Properties props = makePropertiesObject();
        
        Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
                  protected PasswordAuthentication getPasswordAuthentication() {
                          return new PasswordAuthentication(username, password);
                  }
            });
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(admin.getBillingEmail()));

            for(final Employee emp : alarm.getEmployeeCollection()){
                if(!emp.getEmpEmail().isEmpty()){
                    final String emailAddress = emp.getEmpEmail();
                    message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(emailAddress));
                }
            }

            message.setSubject(subjectLine);

            //Create Message Part
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);

            //Create a multipar message
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            //Send the complete message parts.
            message.setContent(multipart);
            Transport.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
    
}
